import crypto from 'crypto-browserify'

const tools = {
  /*  加密字符串  */
  COOKIE_SALT: 'pw__walk',
  TOKEN_SALT: 'gi3dwalk%',
  /* 允许上传的文件类型 */
  /*******************************************************file******************************************************************/
  imgMap: ['jpg', 'jpeg', 'png', 'gif'],
  fileMap: ['txt', 'pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'rar', 'zip'],
  allMap: ['jpg', 'jpeg', 'png', 'gif', 'txt', 'pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'rar', 'zip'],
  /* 文件类型是否合格 */
  isFileTypeOk(suffName, type) {
    type = type === 'Replyimg' ? 'img' : type
    return this[type + 'Map'].includes(suffName)
  },
  /*  文件大小是否符合（单位mb） */
  isFileLess(fileSize, size) {
    return fileSize <= size * 1024 * 1024
  },
  /* 获取文件类型后缀名 */
  getFileSuffix(fileName) {
    return fileName.substring(fileName.lastIndexOf('.') + 1, fileName.length).toLowerCase()
  },
  /*  获取文件大小(mb或者kb) */
  getFileSizeString(fileSize) {
    return fileSize > 1024 * 1024 ? (fileSize / 1024 / 1024).toFixed(2) + 'MB' : (fileSize / 1024).toFixed(2) + 'KB'
  },
  /*******************************************************time******************************************************************/
  /*  获取年月日时分秒 */
  getDateFormatString(type, timestamp) {
    var date = timestamp ? new Date(timestamp) : new Date(),
      dateStr = ''
    var y = date.getFullYear()
    var m = date.getMonth() + 1
    m = m < 10 ? '0' + m : m
    var d = date.getDate()
    d = d < 10 ? '0' + d : d
    var h = date.getHours()
    h = h < 10 ? '0' + h : h
    var min = date.getMinutes()
    min = min < 10 ? '0' + min : min
    var s = date.getSeconds()
    s = s < 10 ? '0' + s : s

    switch (type) {
      case 'md':
        dateStr = m + '-' + d
        break
      case 'mdhms':
        dateStr = m + '-' + d + ' ' + h + ':' + min + ':' + s
        break
      case 'ymd':
        dateStr = y + '-' + m + '-' + d
        break
      case 'ymdhms':
        dateStr = y + '-' + m + '-' + d + ' ' + h + ':' + min + ':' + s
        break
      default:
        dateStr = y + '' + m + '' + d + '' + h + '' + min + '' + s
        break
    }
    return dateStr
  },
  /* 获取格式化的时间戳（距离当前时间有多久） */
  getChatTimeString(timestamp) {
    var currDate = new Date(),
      currTimestamp = currDate.getTime(),
      timeLong = currTimestamp - timestamp,
      timeStr = ''
    if (timeLong <= 60 * 1000) {
      timeStr = '刚刚'
    } else if (timeLong > 60 * 1000 && timeLong <= 2 * 60 * 1000) {
      timeStr = '1分钟前'
    } else if (timeLong > 2 * 60 * 1000 && timeLong <= 60 * 60 * 1000) {
      var min = Math.floor(timeLong / 1000 / 60)
      timeStr = min + '分钟前'
    } else if (timeLong > 60 * 60 * 1000 && timeLong <= 24 * 60 * 60 * 1000) {
      var min = Math.floor(timeLong / 1000 / 60 / 60)
      timeStr = min + '小时前'
    } else if (timeLong > 24 * 60 * 60 * 1000) {
      var currYear = currDate.getFullYear(),
        timeYear = new Date(timestamp).getFullYear()
      if (currYear === timeYear) {
        //今年内
        timeStr = this.getDateFormatString('md', timestamp)
      } else {
        //跨年
        timeStr = this.getDateFormatString('ymd', timestamp)
      }
    }
    return timeStr
  },
  /*******************************************************crypto******************************************************************/
  /* ecb加密(存入cookie使用) */
  getEncrypt(plaintext, salt, iv) {
    var key = new Buffer.from(salt || this.COOKIE_SALT)
    var iv = new Buffer.alloc(iv ? iv : 0)
    var cipher = crypto.createCipheriv('des-ecb', key, iv)
    cipher.setAutoPadding(true) //default true
    var ciph = cipher.update(plaintext, 'utf8', 'base64')
    ciph += cipher.final('base64')
    return ciph
  },
  /*  ecb解密(获取cookie使用) */
  getDecrypt(encrypt_text, salt, iv) {
    var key = new Buffer.from(salt || this.COOKIE_SALT)
    var iv = new Buffer.alloc(iv ? iv : 0)
    var decipher = crypto.createDecipheriv('des-ecb', key, iv)
    decipher.setAutoPadding(true)
    var txt = decipher.update(encrypt_text, 'base64', 'utf8')
    txt += decipher.final('utf8')
    return txt
  },
  /* 参数token加密 */
  getToken(obj) {
    var key = this.TOKEN_SALT
    var str = ''
    var strArr = []
    var sumsArr = []
    str = JSON.stringify(obj) + key
    str = crypto.createHash('md5').update(str, 'utf-8').digest('hex')
    strArr[0] = str.substr(0, 8)
    strArr[1] = str.substr(8, 8)
    strArr[2] = str.substr(16, 8)
    strArr[3] = str.substr(24, 8)
    for (var i = 0; i < strArr.length; i++) {
      var numArr = []
      for (var j = 0; j < strArr[i].length; j++) {
        var c = strArr[i].charAt(j)
        if (c == 'a' || c == 'A') {
          numArr[j] = 10
        } else if (c == 'b' || c == 'B') {
          numArr[j] = 11
        } else if (c == 'c' || c == 'C') {
          numArr[j] = 12
        } else if (c == 'd' || c == 'D') {
          numArr[j] = 13
        } else if (c == 'e' || c == 'E') {
          numArr[j] = 14
        } else if (c == 'f' || c == 'F') {
          numArr[j] = 15
        } else {
          numArr[j] = parseInt(c)
        }
      }
      sumsArr[i] = 0
      for (var k = 0; k < numArr.length; k++) {
        sumsArr[i] += numArr[k]
      }
    }
    sumsArr[0] *= 17
    sumsArr[1] *= 37
    sumsArr[2] *= 23
    sumsArr[3] *= 73
    for (var m = 0; m < sumsArr.length; m++) {
      sumsArr[m] = sumsArr[m] % 25
    }
    var words = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
    var token = ''
    for (var s = 0; s < sumsArr.length; s++) {
      token += words.charAt(sumsArr[s])
    }

    token = crypto.createHash('sha1').update(token).digest('hex')
    return token
  },
  /* 密码md5加密 */
  getMd5(str) {
    const md5 = crypto.createHash('md5')
    return md5.update(str).digest('hex').toString().toUpperCase()
  },
  /*  获取加密AUTH */
  getZJSKAUTH(uid, url) {
    //var str = 'shukebang_' + this.getDateFormatString() + '|' + uid + '|' + url
    var str = 'shukebang_' + '|' + uid + '|' + url
    return encodeURIComponent(this.getEncrypt(str))
  },
  /*******************************************************金额处理******************************************************************/
  //去除逗号
  moneyStr(str) {
    return str.replace(/,/gi, '')
  },
  //逗号分隔
  moneyNum(money) {
    if (money.length <= 3) {
      return money
    }
    if (!/^(\+|-)?(\d+)(\.\d+)?$/.test(money)) {
      return money
    }
    var a = RegExp.$1,
      b = RegExp.$2,
      c = RegExp.$3
    var re = new RegExp()
    re.compile('(\\d)(\\d{3})(,|$)')
    while (re.test(b)) {
      b = b.replace(re, '$1,$2$3')
    }
    return a + '' + b + '' + c
  },
  //逗号分隔并且保留两位小数
  fixed2(num) {
    var val = Math.round(parseFloat(num) * 100) / 100
    var arr = val.toString().split('.')

    if (arr.length === 1) {
      return val.toString() + '.00'
    } else {
      if (arr[1].length < 2) {
        return val.toString() + '0'
      }
      return val + ''
    }
  },
  moneyFix2() {
    var v = this
    if (arguments.length > 0) {
      v = arguments[0]
    }
    var result
    var f_target = parseFloat(v)
    if (isNaN(f_target)) {
    } else {
      //var x = f_target.toFixed(2).split('.')
      var x = this.fixed2(f_target).split('.')
      var x1 = x[0]
      var x2 = x.length > 1 ? '.' + x[1] : ''
      var rgx = /(\d+)(\d{3})/
      while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1,$2')
      }
      result = x1 + x2
      if (x2 == '') {
        result += '.00'
      }
    }
    return result
  },
  //小写
  moneyLower(money) {
    var cnNums = new Array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9')
    var cnIntRadice = new Array('', '', '', '')
    var cnIntUnits = new Array('', ' 万 ', ' 亿 ', '兆')
    var cnDecUnits = new Array('', '', '毫', '厘')
    var cnInteger = ''
    var cnIntLast = ''
    var maxNum = 99999999999.99
    var integerNum
    var decimalNum
    var chineseStr = ''
    var parts
    if (money === '') {
      return ''
    }
    money = parseFloat(money)
    if (money >= maxNum) {
      return ''
    }
    if (money == 0) {
      chineseStr = cnNums[0] + cnIntLast + cnInteger
      return chineseStr
    }
    money = money.toString()
    if (money.indexOf('.') == -1) {
      integerNum = money
      decimalNum = ''
    } else {
      parts = money.split('.')
      integerNum = parts[0]
      decimalNum = parts[1].substr(0, 2)
    }
    if (parseInt(integerNum, 10) >= 0) {
      var zeroCount = 0
      var IntLen = integerNum.length
      for (var i = 0; i < IntLen; i++) {
        var n = integerNum.substr(i, 1)
        var p = IntLen - i - 1
        var q = p / 4
        var m = p % 4
        if (zeroCount > 0) {
          chineseStr += cnNums[0]
        }
        zeroCount = 0

        chineseStr += cnNums[parseInt(n)]

        if (m == 0 && zeroCount < 4) {
          chineseStr += cnIntUnits[q]
        }
      }
      chineseStr
    }
    if (decimalNum != '') {
      var decLen = decimalNum.length,
        $xs = ''
      for (var i = 0; i < decLen; i++) {
        var n = decimalNum.substr(i, 1)
        $xs += cnNums[Number(n)]
      }
      chineseStr += '.' + $xs
    }
    if (chineseStr == '') {
      chineseStr += cnNums[0] + cnIntLast + cnInteger
    } else if (decimalNum == '') {
      chineseStr += cnIntLast + cnInteger
    }
    return chineseStr
  },
  //大写
  moneyUpper(money) {
    var cnNums = new Array('零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖')
    var cnIntRadice = new Array('', '拾', '佰', '仟')
    var cnIntUnits = new Array('', '万', '亿', '兆')
    var cnDecUnits = new Array('角', '分', '毫', '厘')
    var cnInteger = '整'
    var cnIntLast = '元'
    var maxNum = 999999999999999.9999
    var integerNum
    var decimalNum
    var chineseStr = ''
    var parts
    if (money === '') {
      return ''
    }
    money = parseFloat(money)
    if (money >= maxNum) {
      return ''
    }
    if (money == 0) {
      chineseStr = cnNums[0] + cnIntLast + cnInteger
      return chineseStr
    }
    money = money.toString()
    if (money.indexOf('.') == -1) {
      integerNum = money
      decimalNum = ''
    } else {
      parts = money.split('.')
      integerNum = parts[0]
      decimalNum = parts[1].substr(0, 4)
    }
    if (parseInt(integerNum, 10) > 0) {
      var zeroCount = 0
      var IntLen = integerNum.length
      for (var i = 0; i < IntLen; i++) {
        var n = integerNum.substr(i, 1)
        var p = IntLen - i - 1
        var q = p / 4
        var m = p % 4
        if (n == '0') {
          zeroCount++
        } else {
          if (zeroCount > 0) {
            chineseStr += cnNums[0]
          }
          zeroCount = 0
          chineseStr += cnNums[parseInt(n)] + cnIntRadice[m]
        }
        if (m == 0 && zeroCount < 4) {
          chineseStr += cnIntUnits[q]
        }
      }
      chineseStr += cnIntLast
    }
    if (decimalNum != '') {
      var decLen = decimalNum.length
      for (var i = 0; i < decLen; i++) {
        var n = decimalNum.substr(i, 1)
        if (n != '0') {
          chineseStr += cnNums[Number(n)] + cnDecUnits[i]
        }
      }
    }
    if (chineseStr == '') {
      chineseStr += cnNums[0] + cnIntLast + cnInteger
    } else if (decimalNum == '') {
      chineseStr += cnInteger
    }
    return chineseStr
  },
  accAdd(arg1, arg2) {
    //加法
    var r1, r2, m
    try {
      r1 = arg1.toString().split('.')[1].length
    } catch (e) {
      r1 = 0
    }
    try {
      r2 = arg2.toString().split('.')[1].length
    } catch (e) {
      r2 = 0
    }
    m = Math.pow(10, Math.max(r1, r2))
    return (arg1 * m + arg2 * m) / m
  },
  Subtr(arg1, arg2) {
    //减法
    var r1, r2, m, n
    try {
      r1 = arg1.toString().split('.')[1].length
    } catch (e) {
      r1 = 0
    }
    try {
      r2 = arg2.toString().split('.')[1].length
    } catch (e) {
      r2 = 0
    }
    m = Math.pow(10, Math.max(r1, r2))
    n = r1 >= r2 ? r1 : r2
    return ((arg1 * m - arg2 * m) / m).toFixed(n)
  },
  accMul(arg1, arg2) {
    //乘法
    var m = 0,
      s1 = arg1.toString(),
      s2 = arg2.toString()
    try {
      m += s1.split('.')[1].length
    } catch (e) {}
    try {
      m += s2.split('.')[1].length
    } catch (e) {}
    return (Number(s1.replace('.', '')) * Number(s2.replace('.', ''))) / Math.pow(10, m)
  },
  /*******************************************************axios******************************************************************/
  /* 获取单个axios单元 */
  getCoreAxios(env, domain, path, dataToken) {
    var store = env.store ? 'store' : '$store'
    return env.$axios.post(domain + path, env.$qs.stringify(dataToken), {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        cookie_user_id: encodeURIComponent(env[store].state.uid || '0'),
        zjskauth: env.$tools.getZJSKAUTH(env[store].state.uid || '0', domain + path),
        login_guid: env[store].state.guid || '0'
      }
    })
  },
  /* 获取准备发送的axios列表 */
  getDataAxios(env, domain, path, data) {
    var dataAxios = []
    for (var i = 0; i < data.length; i++) {
      dataAxios.push(
        this.getCoreAxios(env, domain[i], path[i], {
          data: JSON.stringify(data[i]),
          token: env.$tools.getToken(data[i])
        })
      )
    }
    return dataAxios
  },
  /* axios回调处理 */
  callbackAxios(env, response, callback) {
    var data = response[0].data
    if (data.code === 40001) {
      //前端操作退出 有提示
      if (env.$alert && !document.querySelector('.el-message-box')) {
        env.$alert('您已经退出登录', '提示', {
          confirmButtonText: '确定'
        })
      }
      this.clearCookie(env)
    } else {
      return callback(response)
    }
  },
  clearCookie(env) {
    //服务器cookie
    //env.$cookies.remove('uid', { domain: '.ccccdt.com', path: '/' })
    env.$cookies.remove('uid')
    env.$cookies.remove('guid')
    env.$cookies.remove('uname')
    env.$cookies.remove('head_img')
    env.$cookies.remove('uphone')
    env.$cookies.remove('pure_user_ids')

    env.$store.commit('setUid', '')
    env.$store.commit('setGuid', '')
    env.$store.commit('setUname', '')
    env.$store.commit('setHeadImg', '')
    env.$store.commit('setUphone', '')
    env.$store.commit('setUphone', '')
    env.$store.commit('setPureUserIds', '')

    env.$socket.close() //关闭socketio
    env.$router.push('/skb_login/') //跳转到首页
  },
  /*******************************************************page******************************************************************/

  /* 上传控件路径处理为数组对象 */
  getUrlToObj(path) {
    let urlList = [],
      objList = []
    if (path && Array.isArray(path)) {
      path = path.join()
    }
    if (path) {
      if (path.indexOf('|') > -1) {
        urlList = path.split('|')
      } else if (path.indexOf(',') > -1) {
        urlList = path.split(',')
      } else {
        urlList = [path]
      }
    }
    urlList = urlList.filter(Boolean)
    objList = urlList.map((item) => {
      var arr = item.split('/'),
        name = arr[arr.length - 1],
        key = arr[arr.length - 1]
      return {
        key: key,
        name: name,
        url: item + '?data=' + this.getZJSKAUTH(item)
      }
    })
    return { urlList, objList }
  },
  /* 获取天翼云sts */
  getStsClient: function (vue, arg, callback) {
    var data = {
        user_id: vue.$store.state.uid
      },
      dataToken = {
        data: JSON.stringify(data),
        token: this.getToken(data)
      }
    vue.$axios
      .post(vue.$store.state.DOMAIN + '/chat/get_oos_sts', vue.$qs.stringify(dataToken), {
        headers: {
          cookie_user_id: encodeURIComponent(vue.$store.state.uid),
          zjskauth: vue.$tools.getZJSKAUTH(vue.$store.state.uid, vue.$store.state.DOMAIN + '/chat/get_oos_sts'),
          login_guid: vue.$store.state.guid || '0'
        }
      })
      .then((res) => {
        var result = res.data
        if (result.code === 200) {
          var bucketName = result.data.STS_BUCKET
          var s3Config = {
            accessKeyId: result.data.STS_ACCESS_KEY_ID,
            secretAccessKey: this.getDecrypt(result.data.STS_ACCESS_KEY_SECRET),
            endpoint: result.data.STS_ENDPOINT,
            sessionToken: result.data.STS_SESSION_TOKEN,
            signatureVersion: 'v4', // 可选v2 或v4
            apiVersion: '2006-03-01',
            s3ForcePathStyle: true
          }
          var client = new OOS.S3(s3Config)
          callback(true, client, bucketName, arg)
        } else {
          vue.$message({
            message: data.message,
            type: 'warning',
            duration: 2000,
            onClose: () => {}
          })
          callback(false)
        }
      })
  },
  /*获取天翼云文件url压缩格式 带data*/
  getStsFileUrl(uid, url, sts) {
    var _url = sts ? url + '@oosImage|' + sts : url
    _url = _url + '?data=' + this.getZJSKAUTH(uid, url)
    //  _url = url.includes('https://www.ccccdt.com/ccccdt/') ? _url + '?data=' + this.getZJSKAUTH(uid, url) : _url
    return _url
  },

  /* 生成获取二维码的Token */
  getWebToken: function () {
    var dateStr = this.getDateFormatString()
    var randomStr = Math.floor(Math.random() * 10000)
    var md5Str = this.getMd5('web_login_' + dateStr + randomStr + 'pw__walk')
    return md5Str
  },
  /* 获取随机文件名 */
  getRandomFileName(file) {
    var str = Math.random() + ''
    return '_' + str.substring(2, 6) + '.' + file.name.split('.')[file.name.split('.').length - 1]
  },
  /* 截取指定长度字符串加省略 */
  getLengthEllipsis(str, start, end) {
    return str.length > 7 ? str.substring(start, end) + '...' : str
  },
  //加载不同尺寸图片居中显示/
  loadImgCenter(e, size, callback) {
    var width = e.target.width,
      height = e.target.height
    if (size) {
      if (width >= height) {
        var scale = height / size,
          ml = (width / scale - size) / 2

        e.target.style.height = '100%'
        e.target.style.marginLeft = '-' + ml + 'px'
      } else {
        var scale = width / size,
          mt = (height / scale - size) / 2
        e.target.style.width = '100%'
        e.target.style.marginTop = '-' + mt + 'px'
      }
    }
    if (callback) {
      callback()
    }
  },
  //刷新路由
  refreshRouter(vue) {
    console.log(vue.query)
    var obj = {},
      path = vue.$route.fullPath.split('?')[0]
    for (var i in vue.query) {
      obj[i] = vue.query[i]
    }
    obj.rt = new Date().getTime()

    vue.$router.push(path + '?' + vue.$qs.stringify(obj))
  },
  /****************************************************************************/
  tabToText: [
    {
      tabName: /^pm-create$/,
      sub: { 0: '创建项目', 1: '设置组织架构', 2: '设置项目节点' }
    },
    { tabName: /^pm-mana-template$/, text: '管理模板' },
    { tabName: /^pm-edit-template-\d{1,5}$/, text: '编辑模板' },
    { tabName: /^pm-add-out$/, text: '添加企业订单' },
    { tabName: /^pm-add-ck$/, text: '添加创客订单' },
    {
      tabName: /^pm-detail-\d{1,5}$/,
      sub: {
        0: '',
        '0-0': '',
        1: '',
        2: '',
        '2-0': '',
        3: '',
        '3-0': '',
        4: '',
        5: ''
      }
    },
    // { tabName: /^pm-detail-\d{1,5}-\d{1,5}/, text: '项目管理资料' },
    {
      tabName: /^pm-list$/,
      sub: { 0: '项目管理', 1: '项目管理', 2: '项目管理', 3: '项目回收站', 4: '项目日志' }
    },
    { tabName: /^wt-list$/, text: '待办任务' },
    { tabName: /^em-list$/, text: '团队成员' },
    { tabName: /^em-import$/, text: '批量导入' },
    { tabName: /^pc-chat$/, text: '私域聊天' },
    { tabName: /^pc-org$/, sub: { 0: '新建高级群聊', 1: '编辑群组织架构' } },
    { tabName: /^ma-list$/, text: '我的审批' },
    { tabName: /^ma-detail$/, text: '审批详情' }
  ],
  // 设置标签页列表 idName是唯一标识，tabName是标签标识 pm-detail-123
  setTabs(vue, suid, type, opt) {
    var matched = this.tabToText.filter((item) => {
        return item.tabName.test(opt.hashName)
      })[0],
      tabs = this.getTabs(vue, suid),
      tabsCookie = {}

    if (!matched) {
      // vue.$router.push('/main/#/pm?tab=list&elTab=0')
    } else {
      var isExistItem = tabs.filter((item) => {
          return item.hashName === opt.hashName
        })[0],
        index = tabs.indexOf(isExistItem)

      if (type === 'open') {
        if (!isExistItem) {
          tabs.push({
            hashName: opt.hashName,
            text: matched.text || matched.sub[opt.elTab],
            fullPath: opt.fullPath,
            elTab: opt.elTab,
            rootProjectId: opt.rootProjectId,
            templateId: opt.templateId,
            groupId: opt.groupId
          })
        } else {
          isExistItem.fullPath = opt.fullPath
          isExistItem.elTab = opt.elTab
          isExistItem.text = matched.text || matched.sub[opt.elTab]
          isExistItem.rootProjectId = opt.rootProjectId
          isExistItem.templateId = opt.templateId
          isExistItem.groupId = opt.groupId
        }
      } else if (type === 'close') {
        tabs.splice(index, 1)
      }
      tabsCookie[suid] = tabs
      vue.$cookies.set('tabs', tabsCookie, { path: '/', maxAge: 60 * 60 * 24 })
      vue.$store.commit('setTabs', JSON.stringify(tabsCookie))
    }
  },
  //获取当前标签页列表
  getTabs(vue, suid) {
    var tabs = vue.$store.state.tabs ? JSON.parse(vue.$store.state.tabs) : {}
    return tabs[suid] ? tabs[suid] : []
  },
  //获取唯一标识名
  getHashName(vue) {
    var hash = vue.$route.hash.split('?')[0].split('/')[1],
      query = vue.$route.hash.split('?')[1] ? vue.$qs.parse(vue.$route.hash.split('?')[1]) : {}
    if (query.tab) {
      if (hash === 'pm') {
        if (query.tab === 'edit-template') {
          return hash + '-' + query.tab + '-' + query.templateId
        } else if (query.tab === 'detail') {
          // if (query.groupId) {
          //   return hash + '-' + query.tab + '-' + query.rootProjectId +'-' + query.groupId
          // }
          return hash + '-' + query.tab + '-' + query.rootProjectId
        } else {
          return hash + '-' + query.tab
        }
      } else {
        return hash + '-' + query.tab
      }
    }
  },
  //获取查询参数
  getQuery(vue) {
    return vue.$route.hash.split('?')[1] ? vue.$qs.parse(vue.$route.hash.split('?')[1]) : {}
  },
  // 文件重命名方法
  getRandomName(file) {
    var str = Math.random() + ''
    return '_' + str.substring(2, 6) + '.' + file.name.split('.')[file.name.split('.').length - 1]
  },
  // 防抖函数
  debounce(func, wait, immediate) {
    let timeout
    return function (...args) {
      const context = this
      const later = function () {
        timeout = null
        if (!immediate) func.apply(context, args)
      }
      const callNow = immediate && !timeout
      clearTimeout(timeout)
      timeout = setTimeout(later, wait)
      if (callNow) func.apply(context, args)
    }
  },
  //文件后缀
  fileTypeName(fileSuffixName) {
    var fileSuffix = fileSuffixName.toLowerCase()
    if (fileSuffix.indexOf('doc') > -1) {
      return 'word'
    } else if (fileSuffix.indexOf('xls') > -1) {
      return 'excle'
    } else if (fileSuffix.indexOf('pdf') > -1) {
      return 'pdf'
    } else if (fileSuffix.indexOf('ppt') > -1) {
      return 'ppt'
    } else if (fileSuffix.indexOf('txt') > -1) {
      return 'txt'
    } else if (fileSuffix.indexOf('mp4') > -1) {
      return 'video'
    } else if (
      fileSuffix.indexOf('jpg') > -1 ||
      fileSuffix.indexOf('jpeg') > -1 ||
      fileSuffix.indexOf('png') > -1 ||
      fileSuffix.indexOf('gif') > -1
    ) {
      return 'pic'
    } else if (fileSuffix.indexOf('zip') > -1 || fileSuffix.indexOf('rar') > -1 || fileSuffix.indexOf('7z') > -1) {
      return 'zip'
    } else {
      return 'unknown'
    }
  },
  //根据文件后缀找图片
  getFilePngByFileSuffix(fileSuffix) {
    if (fileSuffix == 'jpg' || fileSuffix == 'jpeg' || fileSuffix == 'png') {
      return 'pic'
    } else if (fileSuffix == 'doc' || fileSuffix == 'docx') return 'doc'
    else if (fileSuffix == 'xls' || fileSuffix == 'xlsx') return 'excel'
    else if (fileSuffix == 'pdf') return 'pdf'
    else return 'txt'
  },
  convertUnit(bytes) {
    if (bytes < 1024) {
      return bytes + ' B'
    } else if (bytes < 1024 * 1024) {
      return (bytes / 1024).toFixed(2) + ' KB'
    } else if (bytes < 1024 * 1024 * 1024) {
      return (bytes / (1024 * 1024)).toFixed(2) + ' MB'
    } else if (bytes < 1024 * 1024 * 1024 * 1024) {
      return (bytes / (1024 * 1024 * 1024)).toFixed(2) + ' GB'
    } else {
      return (bytes / (1024 * 1024 * 1024 * 1024)).toFixed(2) + ' TB'
    }
  }
}
export default ({ app }, inject) => {
  inject('tools', tools)
}
